<template>
  <div ref="target" class="chart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from "vue";
import * as echarts from "echarts";

interface DataItem {
  new: number;
  active: number;
}

const props = defineProps<{
  data: DataItem[];
}>();

let chart: echarts.ECharts | null = null;
const target = ref<HTMLElement | null>(null);

const ChartInit = () => {
  if (!target.value) return;

  if (chart) {
    chart.dispose();
    chart = null;
  }

  const newSeries = [
    {
      name: "新增",
      type: "bar",
      stack: "Ad",
      emphasis: {
        focus: "series",
      },
      data: props.data.map((item) => item.new),
    },
    {
      name: "活跃",
      type: "bar",
      stack: "Ad",
      emphasis: {
        focus: "series",
      },
      data: props.data.map((item) => item.active),
    },
  ];

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {},
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      },
    ],
    yAxis: [
      {
        type: "value",
      },
    ],
    series: newSeries,
  };

  try {
    chart = echarts.init(target.value);
    chart.setOption(option);
  } catch (error) {
    console.error("Error setting option:", error);
  }
};

const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

let resizeObserver: ResizeObserver | null = null;

onMounted(() => {
  ChartInit();
  resizeObserver = new ResizeObserver(handleResize);
  if (target.value) {
    resizeObserver.observe(target.value);
  }
});

onUnmounted(() => {
  if (resizeObserver && target.value) {
    resizeObserver.unobserve(target.value);
    resizeObserver.disconnect();
  }
  if (chart) {
    chart.dispose();
    chart = null;
  }
});

watch(() => props.data, ChartInit);
</script>

<style lang="less" scoped>
.chart {
  height: 300px;
  width: 100%;
  margin-right: 50px;
}
</style>